<template>
  <div class="job-type-container">
    <div class="job-type-header">
      <h2>工作类别管理</h2>
      <p class="subtitle">管理职位的类别分类信息</p>
    </div>

    <div class="job-type-content">
      <!-- 上部分：表单和提示 -->
      <div class="form-container">
        <div class="form-left">
          <el-form
            ref="jobTypeFormRef"
            :model="jobTypeForm"
            :rules="formRules"
            label-width="80px"
            class="job-type-form"
          >
            <el-form-item label="类别名称" prop="name">
              <el-input
                v-model="jobTypeForm.name"
                placeholder="请输入工作类别名称"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>

            <el-form-item label="排序" prop="sort">
              <el-input-number
                v-model="jobTypeForm.sort"
                :min="0"
                :max="999"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-form>

          <div class="form-actions">
            <el-button @click="clearForm" plain>
              <el-icon><Refresh /></el-icon>
              清空
            </el-button>
            <el-button
              type="primary"
              @click="createJobType"
              :disabled="!canCreate"
            >
              <el-icon><Plus /></el-icon>
              创建
            </el-button>
            <el-button
              type="success"
              @click="updateJobType"
              :disabled="!selectedNode"
            >
              <el-icon><Edit /></el-icon>
              更新
            </el-button>
            <el-button
              type="danger"
              @click="deleteJobType"
              :disabled="!selectedNode"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </div>
        </div>

        <div class="form-right">
          <div class="tips-section">
            <el-alert
              :title="getTipsTitle()"
              type="info"
              :closable="false"
              show-icon
            >
              <div class="tips-content">
                <p>
                  1、【创建】为新增工作类别，未选中类别则创建顶级分类，选中则创建该节点下子分类，最多支持三级分类；
                </p>
                <p>
                  2、【更新】前需要点击任何一项工作类别，在表单中修改后点击【更新】即可提交修改；
                </p>
                <p>3、【删除】前需要选中任何一项工作类别后，方可点击删除；</p>
                <p>4、【清空】清除表单中的待提交信息。</p>
              </div>
            </el-alert>
          </div>
        </div>
      </div>

      <!-- 下部分：树形结构 -->
      <div class="tree-container">
        <div class="tree-header">
          <h3>工作类别结构</h3>
          <div class="tree-actions">
            <el-button
              type="primary"
              text
              @click="refreshData"
              :loading="loading"
            >
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
            <el-button type="warning" text @click="handleRefreshCache">
              <el-icon><Refresh /></el-icon>
              刷新缓存
            </el-button>
          </div>
        </div>

        <el-tree
          v-loading="loading"
          ref="jobTypeTreeRef"
          :data="treeData"
          :props="treeProps"
          :expand-on-click-node="false"
          :load="loadNode"
          lazy
          node-key="id"
          highlight-current
          @node-click="handleNodeClick"
          @node-expand="handleNodeExpand"
          @node-collapse="handleNodeCollapse"
          class="job-type-tree"
          :empty-text="treeData.length === 0 ? '暂无数据' : '加载中...'"
        >
          <template #default="{ data }">
            <div class="tree-node">
              <el-icon class="node-icon">
                <Folder v-if="!data.isLeaf" />
                <Document v-else />
              </el-icon>
              <span class="node-label">{{ data.name }}</span>
              <span class="node-level" :class="`level-${data.level}`">{{
                getLevelText(data.level)
              }}</span>
            </div>
          </template>
        </el-tree>
      </div>
    </div>

    <!-- 缓存刷新对话框 -->
    <el-dialog
      v-model="cacheDialogVisible"
      title="缓存刷新设置"
      width="450px"
      :close-on-click-modal="false"
    >
      <el-form :model="cacheForm" label-width="120px">
        <el-form-item label="刷新日期">
          <el-date-picker
            v-model="cacheForm.refreshDate"
            type="date"
            placeholder="选择刷新日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :disabled-date="disabledDate"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="刷新时间">
          <el-time-picker
            v-model="cacheForm.refreshTime"
            placeholder="选择刷新时间"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item>
          <el-text type="info" size="small">
            选择缓存刷新的具体时间，只能选择当前时间之后的时间点
          </el-text>
        </el-form-item>
        <el-form-item v-if="cacheForm.refreshDate && cacheForm.refreshTime">
          <el-text type="success" size="small">
            延迟时间：{{ getDelaySeconds() }}秒（{{ getDelayText() }}）
          </el-text>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cacheDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="confirmRefreshCache"
            :loading="cacheRefreshing"
            :disabled="!cacheForm.refreshDate || !cacheForm.refreshTime"
          >
            确定刷新
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Plus,
  Edit,
  Delete,
  Refresh,
  Folder,
  Document,
} from "@element-plus/icons-vue";
import {
  getTopList,
  getChildrenList,
  addJobType,
  updateJobType as apiUpdateJobType,
  deleteJobType as apiDeleteJobType,
  refreshJobTypeCache,
} from "@/api/jobType";

// 表单相关
const jobTypeFormRef = ref();
const jobTypeForm = ref({
  name: "",
  sort: 0,
});

const formRules = {
  name: [
    { required: true, message: "请输入工作类别名称", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  sort: [{ required: true, message: "请输入排序值", trigger: "blur" }],
};

// 树形结构相关
const jobTypeTreeRef = ref();
const treeData = ref([]);
const selectedNode = ref(null);
const expandedNodes = ref(new Set());
const childrenCache = ref(new Map());
const loading = ref(false);

// 缓存刷新相关
const cacheDialogVisible = ref(false);
const cacheRefreshing = ref(false);
const cacheForm = ref({
  refreshDate: "",
  refreshTime: "",
});

const treeProps = {
  children: "children",
  label: "name",
  isLeaf: "isLeaf",
  hasChildren: "hasChildren",
};

// 计算属性
const canCreate = computed(() => {
  if (!selectedNode.value) return true; // 可以创建顶级分类
  return selectedNode.value.level < 3; // 支持三级，第三级不能创建子分类
});

// 获取级别文本
const getLevelText = (level) => {
  const levelMap = {
    1: "一级",
    2: "二级",
    3: "三级",
  };
  return levelMap[level] || "";
};

// 获取提示标题
const getTipsTitle = () => {
  if (!selectedNode.value) {
    return "当前未选中任何节点";
  }
  return `当前选中的节点为: ${selectedNode.value.name} (${getLevelText(
    selectedNode.value.level
  )})`;
};

// 计算延迟秒数
const getDelaySeconds = () => {
  if (!cacheForm.value.refreshDate || !cacheForm.value.refreshTime) return 0;
  const refreshDateTime = `${cacheForm.value.refreshDate} ${cacheForm.value.refreshTime}`;
  const refreshTime = new Date(refreshDateTime);
  const currentTime = new Date();
  return Math.max(
    0,
    Math.floor((refreshTime.getTime() - currentTime.getTime()) / 1000)
  );
};

// 获取延迟时间文本
const getDelayText = () => {
  const seconds = getDelaySeconds();
  if (seconds <= 0) return "立即执行";

  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const remainingSeconds = seconds % 60;

  let text = "";
  if (hours > 0) text += `${hours}小时`;
  if (minutes > 0) text += `${minutes}分钟`;
  if (remainingSeconds > 0 || text === "") text += `${remainingSeconds}秒`;

  return text;
};

// 禁用过去的日期
const disabledDate = (date) => {
  return date < new Date();
};

// 处理节点点击
const handleNodeClick = (data, node) => {
  selectedNode.value = data;
  jobTypeForm.value = {
    name: data.name,
    sort: data.sort,
  };
};

// 懒加载节点数据
const loadNode = async (node, resolve) => {
  try {
    if (node.level === 0) {
      // 根节点，加载一级分类
      const data = await getTopList();
      const nodes = data.map((item) => ({
        ...item,
        level: 1,
        hasChildren: !item.isLeaf, // 根据isLeaf判断是否有子节点
      }));
      resolve(nodes);
    } else if (node.level <= 2) {
      // 一级和二级节点，加载子分类
      const data = await getChildrenList(node.data.id);
      const children = data.map((item) => ({
        ...item,
        level: node.level + 1,
        hasChildren: !item.isLeaf, // 根据isLeaf判断是否有子节点
      }));
      resolve(children);
    } else {
      resolve([]);
    }
  } catch (error) {
    ElMessage.error("加载数据失败");
    resolve([]);
  }
};

// 处理节点展开
const handleNodeExpand = (data) => {
  expandedNodes.value.add(data.id);
};

// 处理节点收起
const handleNodeCollapse = (data) => {
  expandedNodes.value.delete(data.id);
};

// 清空表单
const clearForm = () => {
  jobTypeForm.value = {
    name: "",
    sort: 0,
  };
  selectedNode.value = null;
  jobTypeTreeRef.value?.setCurrentKey(null);
};

// 创建工作类别
const createJobType = async () => {
  if (!jobTypeFormRef.value) return;

  await jobTypeFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const params = {
          name: jobTypeForm.value.name,
          sort: jobTypeForm.value.sort,
          fatherId: selectedNode.value ? selectedNode.value.id : "0",
        };

        await addJobType(params);
        ElMessage.success("创建成功");
        clearForm();
        refreshData();
      } catch (error) {
        ElMessage.error("创建失败");
        console.error("创建工作类别失败:", error);
      }
    }
  });
};

// 更新工作类别
const updateJobType = async () => {
  if (!selectedNode.value || !jobTypeFormRef.value) return;

  await jobTypeFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const params = {
          id: selectedNode.value.id,
          name: jobTypeForm.value.name,
          sort: jobTypeForm.value.sort,
        };

        await apiUpdateJobType(params);
        ElMessage.success("更新成功");
        refreshData();
      } catch (error) {
        ElMessage.error("更新失败");
        console.error("更新工作类别失败:", error);
      }
    }
  });
};

// 删除工作类别
const deleteJobType = async () => {
  if (!selectedNode.value) return;

  const levelText = getLevelText(selectedNode.value.level);
  const hasSubCategories =
    selectedNode.value.level < 3 && !selectedNode.value.isLeaf;

  let confirmMessage = `确定要删除工作类别 "${selectedNode.value.name}" (${levelText}) 吗？`;
  if (hasSubCategories) {
    confirmMessage += "此操作将同步删除其下的所有子类别。";
  }

  try {
    await ElMessageBox.confirm(confirmMessage, "删除确认", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    await apiDeleteJobType(selectedNode.value.id);
    ElMessage.success("删除成功");
    clearForm();
    refreshData();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
      console.error("删除工作类别失败:", error);
    }
  }
};

// 刷新数据
const refreshData = async () => {
  // 使用懒加载模式，重新加载根节点数据
  if (jobTypeTreeRef.value) {
    // 清空当前选中的节点
    selectedNode.value = null;
    jobTypeTreeRef.value?.setCurrentKey(null);

    // 重新加载根节点
    jobTypeTreeRef.value.root.loaded = false;
    jobTypeTreeRef.value.root.loadData();

    ElMessage.success("数据已刷新");
  }
};

// 打开缓存刷新对话框
const handleRefreshCache = () => {
  // 设置默认日期和时间为当前时间后10分钟
  const defaultTime = new Date();
  defaultTime.setMinutes(defaultTime.getMinutes() + 10);

  cacheForm.value.refreshDate = defaultTime.toISOString().slice(0, 10);
  cacheForm.value.refreshTime = defaultTime.toTimeString().slice(0, 8);

  cacheDialogVisible.value = true;
};

// 确认刷新缓存
const confirmRefreshCache = async () => {
  if (!cacheForm.value.refreshDate || !cacheForm.value.refreshTime) {
    ElMessage.warning("请选择刷新日期和时间");
    return;
  }

  const delaySeconds = getDelaySeconds();
  if (delaySeconds <= 0) {
    ElMessage.warning("刷新时间必须为当前时间之后");
    return;
  }

  try {
    cacheRefreshing.value = true;

    await refreshJobTypeCache(delaySeconds);

    ElMessage.success(
      `缓存刷新请求已提交，系统将在 ${getDelayText()} 后完成刷新`
    );
    cacheDialogVisible.value = false;
  } catch (error) {
    ElMessage.error("刷新缓存失败");
    console.error("刷新缓存失败:", error);
  } finally {
    cacheRefreshing.value = false;
  }
};

// 初始化
onMounted(() => {
  // 懒加载模式下，树形组件会自动加载根节点数据
});
</script>

<style scoped lang="scss">
.job-type-container {
  padding: 16px;
  background: #ffffff;
  min-height: 100%;
}

.job-type-header {
  margin-bottom: 16px;

  h2 {
    margin: 0 0 4px 0;
    color: #111827;
    font-size: 20px;
    font-weight: 600;
  }

  .subtitle {
    margin: 0;
    color: #6b7280;
    font-size: 14px;
  }
}

.job-type-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

/* 上部分：表单和提示 */
.form-container {
  display: flex;
  gap: 24px;
  align-items: flex-start;

  .form-left {
    flex: 1;
    max-width: 500px;
  }

  .form-right {
    flex: 1;
    min-width: 300px;
  }
}

.job-type-form {
  margin-bottom: 16px;
}

.form-actions {
  display: flex;
  gap: 8px;
  margin-bottom: 16px;

  .el-button {
    flex: 1;
  }
}

.tips-section {
  .el-alert {
    margin-bottom: 0;
  }

  .tips-content {
    margin-top: 8px;

    p {
      margin: 4px 0;
      font-size: 13px;
      line-height: 1.6;
      color: #606266;
    }
  }
}

/* 下部分：树形结构 */
.tree-container {
  .tree-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;

    h3 {
      margin: 0;
      color: #111827;
      font-size: 16px;
      font-weight: 500;
    }

    .tree-actions {
      display: flex;
      gap: 8px;
    }
  }
}

.tree-node {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 0;
  width: 100%;

  .node-icon {
    color: #409eff;
    flex-shrink: 0;
  }

  .node-label {
    flex: 1;
    font-size: 14px;
  }

  .node-level {
    font-size: 12px;
    padding: 2px 6px;
    border-radius: 4px;
    flex-shrink: 0;

    &.level-1 {
      background-color: #e1f3d8;
      color: #67c23a;
    }

    &.level-2 {
      background-color: #ecf5ff;
      color: #409eff;
    }

    &.level-3 {
      background-color: #fdf6ec;
      color: #e6a23c;
    }
  }
}

.job-type-tree {
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  padding: 8px 0;

  .el-tree-node {
    &.is-current > .el-tree-node__content {
      background-color: #f3f4f6;
    }

    .el-tree-node__content {
      height: 40px;
      padding: 0 12px;
      transition: background-color 0.2s;

      &:hover {
        background-color: #f9fafb;
      }
    }
  }
}

/* 对话框样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

// 响应式设计
@media (max-width: 768px) {
  .form-container {
    flex-direction: column;
    gap: 16px;
  }

  .form-left,
  .form-right {
    max-width: none;
    min-width: auto;
  }

  .form-actions {
    flex-direction: column;

    .el-button {
      margin: 2px 0;
    }
  }
}
</style>